package user

import (
	"errors"
	"gitcode.com/G-YT/ANN/server/global"
	"gitcode.com/G-YT/ANN/server/model/manager"
	"gitcode.com/G-YT/ANN/server/model/user"
	userReq "gitcode.com/G-YT/ANN/server/model/user/request"
	userRes "gitcode.com/G-YT/ANN/server/model/user/response"
	"gorm.io/gorm"
)

type UserBindManageService struct {
}

// CreateUserBindManage 创建用户绑定健管师记录
// Author [piexlmax](https://github.com/piexlmax)
func (BindService *UserBindManageService) CreateUserBindManage(Bind *user.UserBindManage) (err error) {
	err = global.GVA_DB.Where("uid = ?", Bind.Uid).Order("created_at Desc").Limit(1).First(&Bind).Error
	if Bind.Status == 1 || Bind.Status == 2 {
		return errors.New("請勿重複提交申請")
	} else {
		Bind = &user.UserBindManage{
			HmId:   Bind.HmId,
			Status: 1,
			Uid:    Bind.Uid,
		}
		err = global.GVA_DB.Create(Bind).Error
	}
	return err
}

// DeleteUserBindManage 删除用户绑定健管师记录
// Author [piexlmax](https://github.com/piexlmax)
func (BindService *UserBindManageService) DeleteUserBindManage(id string) (err error) {
	err = global.GVA_DB.Delete(&user.UserBindManage{}, "id = ?", id).Error
	return err
}

// DeleteUserBindManageByIds 批量删除用户绑定健管师记录
// Author [piexlmax](https://github.com/piexlmax)
func (BindService *UserBindManageService) DeleteUserBindManageByIds(ids []string) (err error) {
	err = global.GVA_DB.Delete(&[]user.UserBindManage{}, "id in ?", ids).Error
	return err
}

// UpdateUserBindManage 更新用户绑定健管师记录
// Author [piexlmax](https://github.com/piexlmax)
func (BindService *UserBindManageService) UpdateUserBindManage(Bind user.UserBindManage) (err error) {
	err = global.GVA_DB.Save(&Bind).Error
	return err
}

// GetBindUserInfoList 获取绑定用户列表
// Author [g-qs](https://gitee.com/g-qs)
func (BindService *UserBindManageService) GetBindUserInfoList(info userReq.UserBindManageSearch) (list []userRes.BindUserInfo, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&user.UserBindManage{}).Where("hm_id = ? AND status = ?", info.HmId, 1).Preload("User")
	var Binds []user.UserBindManage
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}
	err = db.Find(&Binds).Error
	for _, value := range Binds {
		list = append(list, userRes.BindUserInfo{
			ID:       value.ID,
			UserName: value.User.Name,
			Phone:    value.User.Phone,
			Sex:      value.User.Sex,
			Types:    value.User.Types,
			Province: value.User.Province,
			City:     value.User.City,
			Area:     value.User.Area,
		})
	}
	return list, total, err
}

// UpdateBindStatus 修改绑定状态
// Author [g-qs](https://gitee.com/g-qs)
func (BindService *UserBindManageService) UpdateBindStatus(id uint, status string) (err error) {
	return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		var bindInfo user.UserBindManage
		err = tx.Model(&bindInfo).Where("id = ?", id).Update("status", status).Error
		if status == "2" { // 通过审核
			var newHealthManager manager.FdHealthManager
			if bIErr := tx.Where("id = ?", id).First(&bindInfo).Error; bIErr != nil {
				return bIErr
			}
			// 获取新健管师信息
			if nHMErr := tx.Select("store_id,direct_num").Where("hm_id = ?", bindInfo.HmId).First(&newHealthManager).Error; nHMErr != nil {
				return nHMErr
			}
			var userInfo user.User
			// 修改用户信息
			if uIErr := tx.Where("id = ? ", bindInfo.Uid).First(&userInfo).
				Updates(map[string]interface{}{
					"steward_id":        bindInfo.HmId,
					"service_center_id": newHealthManager.StoreId,
				}).Error; uIErr != nil {
				return uIErr
			}
			// 修改健管师信息
			*newHealthManager.DirectNum += 1
			if uErr := tx.Model(&manager.FdHealthManager{}).Where("hm_id = ? ", bindInfo.HmId).Update("direct_num", *newHealthManager.DirectNum).Error; uErr != nil {
				return uErr
			}
		}
		return err
	})
}

// GetUserBindManage 根据id获取用户绑定健管师记录
// Author [piexlmax](https://github.com/piexlmax)
func (BindService *UserBindManageService) GetUserBindManage(id string) (Bind user.UserBindManage, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&Bind).Error
	return
}

// GetUserBindManageInfoList 分页获取用户绑定健管师记录
// Author [piexlmax](https://github.com/piexlmax)
func (BindService *UserBindManageService) GetUserBindManageInfoList(info userReq.UserBindManageSearch) (list []user.UserBindManage, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&user.UserBindManage{})
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.HmId != 0 {
		db = db.Where("hm_id = ?", info.HmId)
	}
	if info.UserBindManage.Status != 0 {
		db = db.Where("status = ?", info.Status)
	}
	if info.UserBindManage.Uid != 0 {
		db = db.Where("uid = ?", info.Uid)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&list).Error
	return list, total, err
}
